package com.lotusfall.mysport.entity;

import com.lotusfall.mysport.controller.UserController;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Weather {
    public String city;
    public String date;
    public String week;
    public String update_time;
    public String wea;
    public String tem;
    public String tem_day;
    public String tem_night;
    public String air;
    public String win_speed;
    public String wea_img;
    JSONObject jsonObject;
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10,TimeUnit.SECONDS)
            .writeTimeout(10,TimeUnit.SECONDS).build();
    private String url = "https://www.yiketianqi.com/free/day?appid=49461919&appsecret=3WCk5arA&unescape=1";

    public Boolean getWeather(String cityCode) throws InterruptedException, JSONException {

        Runnable runnable = new Runnable(){
            @Override
            public void run() {

                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute(); //获取服务器返回的数据
                    String responseData = response.body().string();
                    jsonObject = new JSONObject(responseData);

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        thread.join();
        if(jsonObject != null){
            System.out.println("json:" + jsonObject.toString());
            this.city = jsonObject.get("city").toString();
            this.wea = jsonObject.get("wea").toString();
            this.date = jsonObject.get("date").toString();
            this.week = jsonObject.get("week").toString();
            this.update_time = jsonObject.get("update_time").toString();
            this.tem = jsonObject.get("tem").toString();
            this.air = jsonObject.get("air").toString();
            this.tem_day = jsonObject.get("tem_day").toString();
            this.tem_night = jsonObject.get("tem_night").toString();
            this.win_speed = jsonObject.get("win_speed").toString();
            this.wea_img = jsonObject.get("wea_img").toString();
            return true;

        }else return false;
    }

}
